from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from myadmin import models
from django.core.urlresolvers import reverse
from django.contrib.auth.hashers import make_password, check_password
from project_1.settings import BASE_DIR
import json
# 商品列表
def goodslist(request):
	res1 = request.GET
	try:
		cid = request.GET.get('fen',1)
		# 获取所以分类 一级
		cate = models.Cates.objects.filter(pid=0).exclude(isDelete=True)
		for i in cate:
			i.ad = models.Cates.objects.filter(pid=i.id).exclude(isDelete=True)
			i.cid = str(i.id)
		goo = []
		res = models.Cates.objects.filter(pid=cid).exclude(isDelete=True)
		# # 根据页面传过来的id获取goods对应的数据
		for i in res:
			if request.GET.get("types") == "price":
				for ii in i.goods_set.all().order_by("price").exclude(status=3):
					goo.append(ii)
			else:
				if request.GET.get("types") == "pr":
					for ii in i.goods_set.all().order_by("-ordernum").exclude(status=3):
						goo.append(ii)
				else:
					for ii in i.goods_set.all().exclude(status=3):
						goo.append(ii)
	except:
		goo=[]
	# 全局搜索
	try:
		sou = request.GET.get('sou')
		if 'types' in res1:
			if res1['types'] == "pr":
				goo = models.Goods.objects.filter(title__contains=sou).order_by('-ordernum').exclude(status=3)
			elif res1['types'] == "price":
				goo = models.Goods.objects.filter(title__contains=sou).order_by('price').exclude(status=3)
			else:
				goo = models.Goods.objects.filter(title__contains=sou).exclude(status=3)
		else:
			goo = models.Goods.objects.filter(title__contains=sou).exclude(status=3)
	except:
		pass
	# 默认 价格  人气  搜索
	# try:
	# 	types = request.GET.get("types")
	# 	if types == "price":
	# 		print(goo.order_by("price"))
	# 	else:e
	# 		pass
	# except:
	# 	pass
	# 数据分页
	from django.core.paginator import Paginator
	# 实例化分页类
	paginator = Paginator(goo,10)

	# 获取当前页码
	p = int(request.GET.get('p',1))

	# 获取分页数据对象[{id:1},{id:2}]  [{id:3},{id:4}]
	goodslist= paginator.page(p)

	# 分配数据
	# context = {'goods':goodslist}
	return render(request,'myhome/list.html',{"cate":cate,"goods":goodslist})


# 商品详情
def goodsInfo(request):
	# 获取顶分类
	cate = models.Cates.objects.filter(pid=0).exclude(isDelete=True)
	gid = request.GET.get('id')
	goods1 = models.Goods.objects.get(id=gid)
	return render(request,'myhome/detail.html',{"data":goods1,"cate":cate})


# 购物车
def carts(request):
	
	# 商品id
	gid = request.GET.get("gid")
	# 用户名id
	try:
		uid = request.session.get('vipUser')['id']
	except:
		return HttpResponse("<script>alert('请登录');location.href='/myhome/login'</script>")
	# 添加个数
	num = request.GET.get("num")
	goodsD = models.Goods.objects.get(id=gid)
	user = models.Users.objects.get(id=uid)
	cart = models.Cart.objects.filter(goodsid=goodsD).filter(uid=user)
	if cart:
		for i in cart:
			i.num+=int(num)
			i.save()
	else:
		cart = models.Cart()
		cart.num=num
		cart.uid = user
		cart.goodsid = goodsD
		cart.save()

	return HttpResponse(json.dumps({"error":0,"msg":"添加成功"}))